package com.dede.rxbase.fragment;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dede.rxbase.BuildConfig;
import com.dede.rxbase.util.BLog;

import java.lang.reflect.Field;

/**
 * @author hsh
 *         2018/1/17 18:14.
 */
public abstract class BaseDialogFragment extends DialogFragment {

    private static final boolean HONEYCOMB = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
    private static final String TAG = BuildConfig.DEBUG ? "BaseDialogFragment" : "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getLayoutId(), container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private boolean mIsMulti = false;// 是否已经加载过数据，避免配合切换tab的时候多次加载数据
    private boolean mIsInit = false;// 是否已经初始化过Dialog

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint()) {
            mIsMulti = true;
            BLog.log(this, "initData");
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isVisible() && !mIsMulti) {
            mIsMulti = true;
            BLog.log(this, "initData");
            initData();
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        if (mIsInit) return;
        mIsInit = true;

        initDialog();// 由于有可能修改Dialog的大小，所以在onResume方法内调用该方法
//        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, contentHeight);// 必须放在onResume
    }

    protected void initView() {
    }

    /**
     * 加载数据
     */
    public void initData() {
    }

    /**
     * 初始化Dialog的样式
     */
    protected void initDialog() {
    }

    /**
     * 获取contentViewId
     *
     * @return int 布局资源id
     */
    @LayoutRes
    protected abstract int getLayoutId();

    /**
     * 显示当前DialogFragment
     *
     * @param activity
     */
    public void show(FragmentActivity activity) {
        show(activity.getSupportFragmentManager(), this.getClass().getName());
    }

    /**
     * 显示当前DialogFragment
     *
     * @param fragment
     */
    public void show(Fragment fragment) {
        show(fragment.getChildFragmentManager(), this.getClass().getName());
    }

    @Override
    public int show(FragmentTransaction transaction, String tag) {
        if (HONEYCOMB) {
            return super.show(transaction, tag);
        }
        try {
            Class backStackRecordClass = Class.forName("android.support.v4.app.BackStackRecord");
            Field mManagerField = backStackRecordClass.getDeclaredField("mManager");
            mManagerField.setAccessible(true);
            FragmentManager manager = (FragmentManager) mManagerField.get(transaction);
            boolean stateSaved = manager.isStateSaved();// support v4 26+ api
            if (stateSaved) {
                return showAllowingStateLoss(transaction, tag);
            } else {
                return super.show(transaction, tag);
            }
        } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
            return super.show(transaction, tag);
        }
    }

    /**
     * 显示dialog，忽略状态丢失
     */
    public int showAllowingStateLoss(FragmentTransaction transaction, String tag) {
        try {
            Field mDismissedField = DialogFragment.class.getDeclaredField("mDismissed");
            mDismissedField.setAccessible(true);
            mDismissedField.setBoolean(this, false);

            Field mShownByMeFiled = DialogFragment.class.getDeclaredField("mShownByMe");
            mShownByMeFiled.setAccessible(true);
            mShownByMeFiled.setBoolean(this, true);

            transaction.add(this, tag);

            Field mViewDeclaredFiled = DialogFragment.class.getDeclaredField("mViewDestroyed");
            mViewDeclaredFiled.setAccessible(true);
            mViewDeclaredFiled.setBoolean(this, false);

            Log.i(TAG, "show: by reflect");
            return transaction.commitAllowingStateLoss();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            return super.show(transaction, tag);
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (HONEYCOMB) {
            super.show(manager, tag);
            return;
        }
        boolean stateSaved = manager.isStateSaved();// support v4 26+ api
        if (stateSaved) {
            showAllowingStateLoss(manager, tag);
        } else {
            super.show(manager, tag);
        }
    }

    /**
     * 显示dialog，忽略状态丢失
     */
    public void showAllowingStateLoss(FragmentManager manager, String tag) {
        try {
            Field mDismissedField = DialogFragment.class.getDeclaredField("mDismissed");
            mDismissedField.setAccessible(true);
            mDismissedField.setBoolean(this, false);

            Field mShownByMeFiled = DialogFragment.class.getDeclaredField("mShownByMe");
            mShownByMeFiled.setAccessible(true);
            mShownByMeFiled.setBoolean(this, true);

            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(this, tag);
            transaction.commitAllowingStateLoss();
            Log.i(TAG, "show: by reflect");

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            super.show(manager, tag);
        }
    }

    /**
     * {@inheritDoc}
     * <p>
     * <p>
     * 在{@link FragmentActivity#onSaveInstanceState}方法里面会调用{@link android.support.v4.app.FragmentManagerImpl#saveAllState}，保存Fragment的状态。
     * 在api11（Honeycomb）之前，如果onSaveInstanceState方法被调用，那么肯定是在onPause生命周期方法前，
     * 但api11 以后，却只能保证在onStop生命周期方法前，和onPause方法并没有明确的先后调用顺序，
     * 正是由于此处生命周期的变化，导致api11后，
     * 如果在onPause和onStop之间调用commit，将有可能抛出一个IllegalStateException异常告知状态丢失
     * <a http://blog.csdn.net/edisonchang/article/details/49873669>传送门</a>
     * <p>
     * 例如屏幕关闭时调用了dismiss方法.
     * 方法调用链：
     * onSaveInstanceState=>onStop=>DialogFragment#dismiss=>FragmentTransaction#commit=>throw Exception
     */
    @Override
    public void dismiss() {
        if (isStateSaved() && !HONEYCOMB) {
            super.dismissAllowingStateLoss();
        } else {
            super.dismiss();
        }
    }
}
